import {PassportStrategy} from "@nestjs/passport";
import {ExtractJwt, Strategy, StrategyOptions} from "passport-jwt";
import {ConfigService} from "@nestjs/config";
import {EnvEnum} from "@app/common/enum/envEnum";
import {InjectModel} from "nestjs-typegoose";
import {User} from "@libs/db/models/user.model";
import {Model} from "mongoose";
import {UnauthorizedException} from "@nestjs/common";

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
      private readonly configService: ConfigService,
      @InjectModel(User) private readonly UserModel: Model<User>
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get('env')[EnvEnum.secret] || 'kjdafjdskfioczxuiovjdsfjkds'
    } as StrategyOptions)
  }

  async validate(payload: { id: string }) {
    const user = await this.UserModel.findById(payload.id)
    if (!user) {
      throw new UnauthorizedException()
    }
    return user
  }
}